<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 案例点赞接口
 */
class DesignPraise extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function addDesignPraiseById($designId = NULL)
    {
        if (!$designId) {
            $this->error(__('Parameter %s can not be empty', 'designId'));
        }
        $design = model('\app\admin\model\jy\Design')->where('id', $designId)->find();
        if (!$design) {
            $this->error(__('No Results were found'));
        }
        $userId = $this->auth->id;
        Db::startTrans();
        $row = model('\app\admin\model\jy\DesignPraise')->where(['design_id' => $designId, 'user_id' => $userId])->find();
        if ($row) {
            $row->delete();
            $design['praise_count'] -= 1;
            $design['praise_user_count'] -= 1;
            $design['update_time'] = date("Y-m-d H:i:s", time());
            $design->isUpdate(true)->save();
            Db::commit();
            $this->success('取消点赞', $design['praise_count'], 100);
        }
        try {
            model('\app\admin\model\jy\DesignPraise')->insert(['design_id' => $designId, 'user_id' => $userId]);
            $design['praise_count'] = $design['praise_count'] + 1;
            $design['praise_user_count'] = $design['praise_user_count'] + 1;
            $design['update_time'] = date("Y-m-d H:i:s", time());
            $design->isUpdate(true)->save();
            Db::commit();
            $this->success('点赞成功', $design['praise_count']);
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}
